package com.bwie.filter;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

@Configuration
@Order(1)
public class MyFilter implements GlobalFilter {
    @Autowired
    StringRedisTemplate redisTemplate;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();
        if(path.contains("login")){
            System.out.println("白名单" + path);
            return chain.filter(exchange);
        }
        String token = request.getHeaders().getFirst("token");
        if(token==null){
            System.out.println("token 不存在" + path);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.setComplete();
        }
        Claims body = Jwts.parser().setSigningKey("bwie").parseClaimsJws("key").getBody();
        Integer id = body.get("userId", Integer.class);
        String key = "userId" + id;
        String redisToken = redisTemplate.opsForValue().get(key);
        if(redisToken==null){
            System.out.println("token  已过期" + path);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.setComplete();
        }
        if(!token.equals(redisToken)){
            System.out.println("token 错误 " +path);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.setComplete();
        }
        redisTemplate.expire(key,30, TimeUnit.MINUTES);

        return chain.filter(exchange);
    }
}
